package com.fjnu.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class GlobalExceptionAspect {

    /**
     * 拦截Service层所有方法，进行异常处理
     */
    @Around("execution(* com.fjnu.service.*.*(..))")
    public Object handleServiceException(ProceedingJoinPoint joinPoint) {
        try {
            return joinPoint.proceed();
        } catch (Throwable e) {
            logException(joinPoint, e);
            return getDefaultReturnValue(joinPoint);
        }
    }

    /**
     * 记录异常信息
     */
    private void logException(ProceedingJoinPoint joinPoint, Throwable e) {
        String className = joinPoint.getTarget().getClass().getSimpleName();
        String methodName = joinPoint.getSignature().getName();

        System.err.println("=== Service层异常 ===");
        System.err.println("类名: " + className);
        System.err.println("方法: " + methodName);
        System.err.println("异常: " + e.getClass().getSimpleName());
        System.err.println("信息: " + e.getMessage());
        System.err.println("====================");
        e.printStackTrace();
    }

    /**
     * 根据方法返回类型返回合适的默认值
     */
    private Object getDefaultReturnValue(ProceedingJoinPoint joinPoint) {
        Class<?> returnType = ((org.aspectj.lang.reflect.MethodSignature) joinPoint.getSignature()).getReturnType();

        // 基本类型和包装类型的处理
        if (returnType == int.class || returnType == Integer.class) {
            return 0;
        }
        if (returnType == long.class || returnType == Long.class) {
            return 0L;
        }
        if (returnType == boolean.class || returnType == Boolean.class) {
            return false;
        }
        if (returnType == double.class || returnType == Double.class) {
            return 0.0;
        }
        if (returnType == float.class || returnType == Float.class) {
            return 0.0f;
        }
        if (returnType == void.class) {
            return null;
        }

        // 其他对象类型返回null
        return null;
    }
}